import express from 'express';
import { AgentMCPBridge, AgentConfig } from '../core/agent-mcp-bridge';

export function createAgentServer() {
  const app = express();
  app.use(express.json());
  
  const agents: Map<string, AgentMCPBridge> = new Map();
  
  app.post('/agents', async (req, res) => {
    try {
      const config: AgentConfig = req.body;
      
      if (!config.name || !config.mcpClients) {
        return res.status(400).json({ error: 'Missing required fields: name, mcpClients' });
      }
      
      const agent = new AgentMCPBridge(config);
      await agent.initialize();
      
      agents.set(config.name, agent);
      
      res.json({ 
        success: true, 
        message: `Agent ${config.name} created successfully`,
        status: agent.getStatus()
      });
      
    } catch (error) {
      console.error('Error creating agent:', error);
      res.status(500).json({ error: 'Failed to create agent' });
    }
  });
  
  app.get('/agents/:name', (req, res) => {
    const agent = agents.get(req.params.name);
    if (!agent) {
      return res.status(404).json({ error: 'Agent not found' });
    }
    
    res.json(agent.getStatus());
  });
  
  app.post('/agents/:name/chat', async (req, res) => {
    try {
      const agent = agents.get(req.params.name);
      if (!agent) {
        return res.status(404).json({ error: 'Agent not found' });
      }
      
      const { message } = req.body;
      if (!message) {
        return res.status(400).json({ error: 'Message is required' });
      }
      
      const response = await agent.processMessage({
        role: 'user',
        content: message
      });
      
      res.json(response);
      
    } catch (error) {
      console.error('Error processing message:', error);
      res.status(500).json({ error: 'Failed to process message' });
    }
  });
  
  app.get('/agents/:name/tools', (req, res) => {
    const agent = agents.get(req.params.name);
    if (!agent) {
      return res.status(404).json({ error: 'Agent not found' });
    }
    
    res.json(agent.getAvailableTools());
  });
  
  app.get('/agents/:name/resources', (req, res) => {
    const agent = agents.get(req.params.name);
    if (!agent) {
      return res.status(404).json({ error: 'Agent not found' });
    }
    
    res.json(agent.getAvailableResources());
  });
  
  app.delete('/agents/:name', async (req, res) => {
    try {
      const agent = agents.get(req.params.name);
      if (!agent) {
        return res.status(404).json({ error: 'Agent not found' });
      }
      
      await agent.shutdown();
      agents.delete(req.params.name);
      
      res.json({ success: true, message: `Agent ${req.params.name} shutdown successfully` });
      
    } catch (error) {
      console.error('Error shutting down agent:', error);
      res.status(500).json({ error: 'Failed to shutdown agent' });
    }
  });
  
  app.get('/agents', (req, res) => {
    const agentList = Array.from(agents.entries()).map(([agentName, agent]) => {
      const status = agent.getStatus();
      return {
        id: agentName,
        ...status
      };
    });
    
    res.json(agentList);
  });
  
  return app;
}

async function startServer() {
  const app = createAgentServer();
  const port = process.env.PORT || 3000;
  
  app.listen(port, () => {
    console.log(`Agent MCP Server running on port ${port}`);
    console.log(`Available endpoints:`);
    console.log(`  POST   /agents     - Create a new agent`);
    console.log(`  GET    /agents     - List all agents`);
    console.log(`  GET    /agents/:name - Get agent status`);
    console.log(`  POST   /agents/:name/chat - Send message to agent`);
    console.log(`  GET    /agents/:name/tools - Get agent tools`);
    console.log(`  GET    /agents/:name/resources - Get agent resources`);
    console.log(`  DELETE /agents/:name - Shutdown agent`);
  });
}

if (require.main === module) {
  startServer().catch(console.error);
}

export { startServer };